package com.jack.leetcode.eachProblem08;

import java.util.Arrays;

public class _24点游戏 {

    public static void main(String[] args) {
        new _24点游戏().judgePoint24(new int[]{1, 2, 1, 2});
    }

    public boolean judgePoint24(int[] nums) {
        return judge(Arrays.stream(nums).asDoubleStream().toArray());
    }

    public boolean judge(double[] nums) {
        int n = nums.length;
        if (n == 1) {
            return nums[0] > 23.999 && nums[0] < 24.001;
        }
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                double[] tmp = new double[n - 1];
                System.arraycopy(nums, 0, tmp, 0, j);
                System.arraycopy(nums, j + 1, tmp, j, n - j - 1);
                boolean isValid = false;
                tmp[i] = nums[i] + nums[j];
                isValid = isValid || judge(tmp);

                tmp[i] = nums[i] - nums[j];
                isValid = isValid || judge(tmp);
                tmp[i] = nums[j] - nums[i];
                isValid = isValid || judge(tmp);

                tmp[i] = nums[i] * nums[j];
                isValid = isValid || judge(tmp);

                if (nums[j] != 0) {
                    tmp[i] = nums[i] / nums[j];
                    isValid = isValid || judge(tmp);
                }
                if (nums[i] != 0) {
                    tmp[i] = nums[j] / nums[i];
                    isValid = isValid || judge(tmp);
                }
                if (isValid) {
                    return true;
                }
            }
        }
        return false;
    }
}
